/*
 * VenoBox - jQuery Plugin
 * version: 1.5.3
 * @requires jQuery
 *
 * Examples at http://lab.veno.it/venobox/
 * License: MIT License
 * License URI: https://github.com/nicolafranchini/VenoBox/blob/master/LICENSE
 * Copyright 2013-2015 Nicola Franchini - @nicolafranchini
 *
 */
(function ($) {

	var bgcolor, blocknum, blocktitle, border, core, container, content, dest,
		evitacontent, evitanext, evitaprev, extraCss, figliall, framewidth, frameheight,
		infinigroup, items, keyNavigationDisabled, margine, numeratio, overlayColor, overlay, overlayclose,
		prima, title, thisgroup, thenext, theprev, type,
		finH, sonH, nextok, prevok;

	$.fn.extend({
		//plugin name - venobox
		venobox: function (options) {

			// default option
			var defaults = {
				framewidth: '',
				frameheight: '',
				border: '0',
				bgcolor: '',
				titleattr: 'title', // specific attribute to get a title (e.g. [data-title]) - thanx @mendezcode
				numeratio: false,
				infinigroup: false,
				overlayclose: true // disable overlay click-close - thanx @martybalandis
			};

			var option = $.extend(defaults, options);

			return this.each(function () {
				var obj = $(this);

				// Prevent double initialization - thanx @matthistuff
				if (obj.data('venobox')) {
					return true;
				}

				obj.addClass('vbox-item');
				obj.data('venobox', true);

				obj.click(function (e) {
					e.stopPropagation();
					e.preventDefault();
					obj = $(this);
					overlayColor = obj.data('overlay') || (option.overlayColor || '');
					overlayclose = obj.data('overlayclose') || option.overlayclose;
					framewidth = obj.data('width') || option.framewidth;
					frameheight = obj.data('height') || option.frameheight;
					border = obj.data('border') || option.border;
					bgcolor = obj.data('bgcolor') || option.bgcolor;
					infinigroup = obj.data('infinigroup') || option.infinigroup;
					numeratio = obj.data('numeratio') || option.numeratio;

					if(!bgcolor && this.tagName != 'IMG'){
						bgcolor = '#fff';
					}

					nextok = false;
					prevok = false;
					keyNavigationDisabled = false;
					dest = obj.data('href') || (obj.attr('src') || obj.attr('href'));
					extraCss = obj.data('css') || "";

					$('body').addClass('vbox-open');
					core = '<div class="vbox-overlay ' + extraCss + '" style="background:' + overlayColor + '"><div class="vbox-preloader">Loading...</div><div class="vbox-container"><div class="vbox-content"></div></div><div class="vbox-title"></div><div class="vbox-num">0/0</div><div class="vbox-close">X</div><div class="vbox-next">next</div><div class="vbox-prev">prev</div></div>';

					$('body').append(core);

					overlay = $('.vbox-overlay');
					container = $('.vbox-container');
					content = $('.vbox-content');
					blocknum = $('.vbox-num');
					blocktitle = $('.vbox-title');

					content.html('');
					content.css('opacity', '0');

					checknav();

					overlay.css('min-height', $(window).outerHeight());

					// fade in overlay
					overlay.animate({opacity: 1}, 250, function () {

						if (obj.data('type') == 'iframe') {
							loadIframe();
						} else if (obj.data('type') == 'inline') {
							loadInline();
						} else if (obj.data('type') == 'ajax') {
							loadAjax();
						} else if (obj.data('type') == 'vimeo') {
							loadVimeo();
						} else if (obj.data('type') == 'youtube') {
							loadYoutube();
						} else {
							content.html('<img src="' + dest + '">');
							preloadFirst();
						}
					});

					/* -------- CHECK NEXT / PREV -------- */
					function checknav() {

						thisgroup = obj.data('group');

						items = $('.vbox-item[data-group="' + thisgroup + '"]');

						if (items.length > 0 && numeratio === true) {
							blocknum.html(items.index(obj) + 1 + ' / ' + items.length);
							blocknum.show();
						} else {
							blocknum.hide();
						}

						thenext = items.eq(items.index(obj) + 1);
						theprev = items.eq(items.index(obj) - 1);

						if (obj.attr(option.titleattr)) {
							title = obj.attr(option.titleattr);
							blocktitle.show();
						} else {
							title = '';
							blocktitle.hide();
						}

						if (items.length > 0 && infinigroup === true) {

							nextok = true;
							prevok = true;

							if (thenext.length < 1) {
								thenext = items.eq(0);
							}
							if (items.index(obj) < 1) {
								theprev = items.eq(items.index(items.length));
							}

						} else {

							if (thenext.length > 0) {
								$('.vbox-next').css('display', 'block');
								nextok = true;
							} else {
								$('.vbox-next').css('display', 'none');
								nextok = false;
							}
							if (items.index(obj) > 0) {
								$('.vbox-prev').css('display', 'block');
								prevok = true;
							} else {
								$('.vbox-prev').css('display', 'none');
								prevok = false;
							}
						}
					}

					/* -------- NAVIGATION CODE -------- */
					var groupnav = {

						prev: function () {

							if (keyNavigationDisabled) {
								return;
							} else {
								keyNavigationDisabled = true;
							}

							overlayColor = theprev.data('overlay');

							framewidth = theprev.data('framewidth');
							frameheight = theprev.data('frameheight');
							border = theprev.data('border');
							bgcolor = theprev.data('bgcolor');

							dest = theprev.data('href') || (theprev.attr('src') || theprev.attr('href'));

							if (theprev.attr(option.titleattr)) {
								title = theprev.attr(option.titleattr);
							} else {
								title = '';
							}

							if (overlayColor === undefined) {
								overlayColor = "";
							}

							content.animate({opacity: 0}, 500, function () {

								overlay.css('background', overlayColor);

								if (theprev.data('type') == 'iframe') {
									loadIframe();
								} else if (theprev.data('type') == 'inline') {
									loadInline();
								} else if (theprev.data('type') == 'ajax') {
									loadAjax();
								} else if (theprev.data('type') == 'youtube') {
									loadYoutube();
								} else if (theprev.data('type') == 'vimeo') {
									loadVimeo();
								} else {
									content.html('<img src="' + dest + '">');
									preloadFirst();
								}
								obj = theprev;
								checknav();
								keyNavigationDisabled = false;
							});

						},

						next: function () {

							if (keyNavigationDisabled) {
								return;
							} else {
								keyNavigationDisabled = true;
							}

							overlayColor = thenext.data('overlay');

							framewidth = thenext.data('framewidth');
							frameheight = thenext.data('frameheight');
							border = thenext.data('border');
							bgcolor = thenext.data('bgcolor');
							dest = thenext.data('href') || (thenext.attr('src') || thenext.attr('href'));

							if (thenext.attr(option.titleattr)) {
								title = thenext.attr(option.titleattr);
							} else {
								title = '';
							}

							if (overlayColor === undefined) {
								overlayColor = "";
							}

							content.animate({opacity: 0}, 500, function () {

								overlay.css('background', overlayColor);

								if (thenext.data('type') == 'iframe') {
									loadIframe();
								} else if (thenext.data('type') == 'inline') {
									loadInline();
								} else if (thenext.data('type') == 'ajax') {
									loadAjax();
								} else if (thenext.data('type') == 'youtube') {
									loadYoutube();
								} else if (thenext.data('type') == 'vimeo') {
									loadVimeo();
								} else {
									content.html('<img src="' + dest + '">');
									preloadFirst();
								}
								obj = thenext;
								checknav();
								keyNavigationDisabled = false;
							});

						}

					};

					/* -------- NAVIGATE WITH ARROW KEYS -------- */
					$('body').keydown(function (e) {

						if (e.keyCode == 37 && prevok == true) { // left
							groupnav.prev();
						}

						if (e.keyCode == 39 && nextok == true) { // right
							groupnav.next();
						}

					});

					/* -------- PREVGROUP -------- */
					$('.vbox-prev').click(function () {
						groupnav.prev();
					});

					/* -------- NEXTGROUP -------- */
					$('.vbox-next').click(function () {
						groupnav.next();
					});

					/* -------- ESCAPE HANDLER -------- */
					function escapeHandler(e) {
						if (e.keyCode === 27) {
							closeVbox();
						}
					}

					/* -------- CLOSE VBOX -------- */

					function closeVbox() {

						$('body').removeClass('vbox-open');
						$('body').unbind('keydown', escapeHandler);

						overlay.animate({opacity: 0}, 500, function () {
							overlay.remove();
							keyNavigationDisabled = false;
							obj.focus();
						});
					}

					/* -------- CLOSE CLICK -------- */
					var closeclickclass = '.vbox-close, .vbox-overlay';
					if (!overlayclose) {
						closeclickclass = '.vbox-close';    // close only on X
					}

					$(closeclickclass).click(function (e) {
						evitacontent = '.figlio';
						evitaprev = '.vbox-prev';
						evitanext = '.vbox-next';
						figliall = '.figlio *';
						if (!$(e.target).is(evitacontent) && !$(e.target).is(evitanext) && !$(e.target).is(evitaprev) && !$(e.target).is(figliall)) {
							closeVbox();
						}
					});
					$('body').keydown(escapeHandler);
					return false;
				});
			});
		}
	});

	/* -------- LOAD AJAX -------- */
	function loadAjax() {
		$.ajax({
			url: dest,
			cache: false
		}).done(function (msg) {
			content.html('<div class="vbox-inline">' + msg + '</div>');
			updateoverlay(true);

		}).fail(function () {
			content.html('<div class="vbox-inline"><p>Error retrieving contents, please retry</div>');
			updateoverlay(true);
		})
	}

	/* -------- LOAD IFRAME -------- */
	function loadIframe() {
		content.html('<iframe class="venoframe" src="' + dest + '"></iframe>');
		//  $('.venoframe').load(function(){ // valid only for iFrames in same domain
		updateoverlay();
		//  });
	}

	/* -------- LOAD VIMEO -------- */
	function loadVimeo() {
		var pezzi = dest.split('/');
		var videoid = pezzi[pezzi.length - 1];
		content.html('<iframe class="venoframe" src="//player.vimeo.com/video/' + videoid + '"></iframe>');
		updateoverlay();
	}

	/* -------- LOAD YOUTUBE -------- */
	function loadYoutube() {
		var pezzi = dest.split('/');
		var videoid = pezzi[pezzi.length - 1];
		content.html('<iframe class="venoframe" allowfullscreen src="//www.youtube.com/embed/' + videoid + '"></iframe>');
		updateoverlay();
	}

	/* -------- LOAD INLINE -------- */
	function loadInline() {
		content.html('<div class="vbox-inline">' + $(dest).html() + '</div>');
		updateoverlay();
	}

	/* -------- PRELOAD IMAGE -------- */
	function preloadFirst() {
		prima = $('.vbox-content').find('img');
		prima.one('load', function () {
			updateoverlay();
		}).each(function () {
			if (this.complete) $(this).load();
		});
	}

	/* -------- CENTER ON LOAD -------- */
	function updateoverlay() {

		blocktitle.html(title);
		content.find(">:first-child").addClass('figlio');
		$('.figlio').css('width', framewidth).css('height', frameheight).css('padding', border).css('background', bgcolor);

		sonH = content.outerHeight();
		finH = $(window).height();

		if (sonH + 80 < finH) {
			margine = (finH - sonH) / 2;
			content.css('margin-top', margine);
			content.css('margin-bottom', margine);

		} else {
			content.css('margin-top', '40px');
			content.css('margin-bottom', '40px');
		}
		content.animate({
			'opacity': '1'
		}, 'slow');
	}

	/* -------- CENTER ON RESIZE -------- */
	function updateoverlayresize() {
		if ($('.vbox-content').length) {
			sonH = content.height();
			finH = $(window).height();

			if (sonH + 80 < finH) {
				margine = (finH - sonH) / 2;
				content.css('margin-top', margine);
				content.css('margin-bottom', margine);
			} else {
				content.css('margin-top', '40px');
				content.css('margin-bottom', '40px');
			}
		}
	}

	$(window).resize(function () {
		updateoverlayresize();
	});

})(jQuery);